﻿var cells = [];
var cellSize = 50;
var mousedown = false;
var resource = "url(\"images/stone.gif\")";
var leftStart = 0;
var topStart = 0;
var centerY = 10;
var centerX = 10;
var centerPixelX = 0;
var centerPixelY = 0;
var rightEnd;
var bottomEnd;
var zoom = 1;
var oCenterMarker;
var oMouseOverMarker;
var fov = 10; //field of view. higher the number the smaller the distortion
var minXindex = 0; //minimum value for cells x index
var minYindex = 0; //minimum value for cells y index
var bgRenderReset = true;
var bgInterval;
var bgRenderIterationsMax = 100;
var bgRenderRadius = 1;
var bgRenderDirection = 0; //0 = up, 1 = left, 2 = down, 3 = right
var bgRenderMatrix = [[-1,0],[0,-1],[1,0],[0,1]]; //increments to use with direction
var bgRenderLegIndex = 0;
var bgRenderZ = 0;
var bgRenderY = 0;
var bgRenderX = 0;
function resizeScreen() {
    $("#mapArea").css("height", $(window).height() - 40);
    calcMapVars();
    renderMap();
}
function addCells(e, x, y) {
    var el = $("#cboElevation").val();
    var tmp;
    if (el > 0) {
        if (cells[y] === undefined) {
            cells[y] = [];
        }
        for (var z = 1; z <= el; z++) {
            if (cells[y][x] === undefined) {
                cells[y][x] = [];
            }
            tmp = new cellLayer();
            cells[y][x][z] = tmp;
            tmp.x(x);
            tmp.y(y);
            tmp.resource(resource);
            tmp.elevation(z);
            tmp.render({ append: true });
        }
        if (y < minYindex) {
            minYindex = y;
        }
        if (x < minXindex) {
            minXindex = x;
        }
    }
}
function updateCells(e, x, y) {
    var el = $("#cboElevation").val();
    for (var z = 1; z <= 5; z++) {
        if (cells[y][x] != undefined) {
            if (cells[y][x][z] != undefined) {
                cells[y][x][z].ui.remove();
            }
            cells[y][x][z] = undefined;
        }
    }
    if (el > 0) {
        for (var z = 1; z <= el; z++) {
            cells[y][x][z] = new cellLayer();
            cells[y][x][z].x(x);
            cells[y][x][z].y(y);
            cells[y][x][z].resource(resource);
            cells[y][x][z].elevation(z);
            cells[y][x][z].render({ append: true });
        }
    }
}
function clearScreen() {
    cells = [];
    if (localStorage) {
        localStorage.simpleCells = undefined;
    }
    $("#mapArea").html("");
}
function saveMap() {
    if (localStorage) {
        var simpleCells = [];
        for (var y = minYindex; y < cells.length; y++) {
            if (cells[y] != null) {
                simpleCells[y - minYindex] = [];
                for (var x = minXindex; x < cells[y].length; x++) {
                    if (cells[y][x] != null) {
                        simpleCells[y - minYindex][x - minXindex] = [];
                        for (var z = 1; z <= 5; z++) {
                            if (cells[y][x][z] != null) {
                                simpleCells[y - minYindex][x - minXindex][z] = { "_x": x - minXindex, "_y": y - minYindex, "_elevation": z, "_resource": cells[y][x][z]._resource };
                            }
                        }
                    }
                }
            }
        }
        localStorage.simpleCells = JSON.stringify(simpleCells);
        localStorage.centerX = centerX - minXindex;
        localStorage.centerY = centerY - minYindex;
        localStorage.zoom = zoom;
        alert("saved");
    }
}
function loadMap() {
    if (localStorage) {
        $("#mapArea").html("");
        minXindex = 0;
        minYindex = 0;
        var simpleCells = JSON.parse(localStorage.simpleCells);
        cells = [];
        for (var y = 0; y < simpleCells.length; y++) {
            if (simpleCells[y] != null) {
                cells[y] = [];
                for (var x = 0; x < simpleCells[y].length; x++) {
                    if (simpleCells[y][x] != null) {
                        cells[y][x] = [];
                        for (var z = 1; z <= 5; z++) {
                            if (simpleCells[y][x][z] != null) {
                                var tmp = new cellLayer();
                                cells[y][x][z] = tmp;
                                tmp.x(x);
                                tmp.y(y);
                                tmp.elevation(z);
                                if (simpleCells[y][x][z]._resource == undefined) {
                                    tmp.resource("url(\"images/stone.gif\")");
                                } else {
                                    tmp.resource(simpleCells[y][x][z]._resource);
                                }
                            }
                        }
                    }
                }
            }
        }
        centerX = Number(localStorage.centerX);
        centerY = Number(localStorage.centerY);
        zoom = Number(localStorage.zoom);
        bgRenderReset = true;
        calcMapVars();
        renderMap();
    }
}
function buildResourceMenu() {
    $("body").append("<div id=\"resourceMenu\"></div>");
    var tmp = $("<div class=\"menuItem\"></div>");
    $("#resourceMenu").append(tmp);
    tmp.css("background-image", "url(\"images/stone.gif\")");
    tmp = $("<div class=\"menuItem\"></div>");
    $("#resourceMenu").append(tmp);
    tmp.css("background-image", "url(\"images/water.gif\")");
    tmp = $("<div class=\"menuItem\"></div>");
    $("#resourceMenu").append(tmp);
    tmp.css("background-image", "url(\"images/brick.gif\")");
    tmp = $("<div class=\"menuItem\"></div>");
    $("#resourceMenu").append(tmp);
    tmp.css("background-image", "url(\"images/grass.gif\")");
    tmp = $("<div class=\"menuItem\"></div>");
    $("#resourceMenu").append(tmp);
    tmp.css("background-image", "url(\"images/cobble.gif\")");
    tmp = $("<div class=\"menuItem\"></div>");
    $("#resourceMenu").append(tmp);
    tmp.css("background-image", "url(\"images/dirt.gif\")");
    $("#resourceMenu").click(function (e) {
        $("#resourceMenu").css("display", "");
        resource = $(e.target).css("background-image");
        $("#btnResource").css("background-image", resource);
    });
}
function openResourceMenu() {
    $("#resourceMenu").css("display", "block");
}
function calcMapVars() {
    var mapWidth = $("#mapArea").innerWidth();
    var mapHeight = $("#mapArea").innerHeight();
    centerPixelX = Math.round(mapWidth / 2);
    centerPixelY = Math.round(mapHeight / 2);
    var mapHalfWidth = (mapWidth / 2) / (cellSize * zoom);
    var mapHalfHeight = (mapHeight / 2) / (cellSize * zoom);
    if (centerY === undefined) {
        centerY = Math.round(mapHalfHeight);
        centerX = Math.round(mapHalfWidth);
    }
    leftStart = centerX - Math.ceil(mapHalfWidth);
    topStart = centerY - Math.ceil(mapHalfHeight);
    rightEnd = centerX + Math.ceil(mapHalfWidth);
    bottomEnd = centerY + Math.ceil(mapHalfHeight);
    //console.log(leftStart, topStart, centerX, centerY, rightEnd, bottomEnd, Math.ceil(mapHalfWidth), Math.ceil(mapHalfHeight));
}
function renderMap() {
    bgInterval = window.clearInterval(bgInterval);
    if (bgRenderReset == true) {
        bgRenderReset = false;
        $("#mapArea").html("");
        bgRenderRadius = 0;
        bgRenderDirection = 3;
        bgRenderLegIndex = 1;
        bgRenderY = centerY;// topStart;
        bgRenderX = centerX;// leftStart;
        bgRenderZ = 1;
    }
    var i = 0;
    while (i < bgRenderIterationsMax && bgRenderZ <= 5) {
        if (bgRenderX > rightEnd && bgRenderY > bottomEnd) {
            bgRenderRadius = 0;
            bgRenderDirection = 3;
            bgRenderLegIndex = 1;
            bgRenderY = centerY;
            bgRenderX = centerX;
            bgRenderZ++;
        }        
        if (cells[bgRenderY] != undefined) {
            if (cells[bgRenderY][bgRenderX] != undefined) {
                if (cells[bgRenderY][bgRenderX][bgRenderZ] != undefined) {
                    cells[bgRenderY][bgRenderX][bgRenderZ].x(bgRenderX);
                    cells[bgRenderY][bgRenderX][bgRenderZ].y(bgRenderY);
                    cells[bgRenderY][bgRenderX][bgRenderZ].elevation(bgRenderZ);
                    cells[bgRenderY][bgRenderX][bgRenderZ].render({ append: true });
                    i++;
                }
            }
        }
        bgRenderLegIndex++;
        if (bgRenderLegIndex > bgRenderRadius) {
            bgRenderLegIndex = 1;
            bgRenderDirection++;
        }
        if (bgRenderDirection > 3) {
            bgRenderDirection = 0;
            bgRenderRadius+=2;
            bgRenderX++;
        } else {
            bgRenderY = bgRenderY + bgRenderMatrix[bgRenderDirection][0];
            bgRenderX = bgRenderX + bgRenderMatrix[bgRenderDirection][1];
        }
    }
    oMouseOverMarker.elevation($("#cboElevation").val());
    $("#mapArea").append(oMouseOverMarker.ui);
    //oCenterMarker.render();
    if (bgRenderZ <= 5) {
        bgInterval = window.clearInterval(bgInterval);
        bgInterval = window.setInterval(renderMap, 10);
    }
}
function setZoom(p) {
    if (p < .2) {
        p = .2;
    }
    zoom = p;
    bgRenderReset = true;
    calcMapVars();
    renderMap();
}
$(document).ready(function () {
    $("body").append("<div id=\"toolbar\"></div>");
    $("#toolbar").append("<select id=\"cboElevation\"><option value=\"0\">0</option><option value=\"1\" selected>1</option><option value=\"2\">2</option><option value=\"3\">3</option><option value=\"4\">4</option><option value=\"5\">5</option></select>");
    $("#toolbar").append("<button id=\"btnClear\">Clear</button>");
    $("#toolbar").append("<button id=\"btnSave\">Save</button>");
    $("#toolbar").append("<button id=\"btnLoad\">Load</button>");
    $("#toolbar").append("<button id=\"btnResource\"></button>");
    $("#btnResource").css("background-image", resource);
    $("#btnResource").click(openResourceMenu);
    buildResourceMenu();
    $("#btnClear").click(clearScreen);
    $("#btnSave").click(saveMap);
    $("#btnLoad").click(loadMap);
    $("body").append("<div id=\"mapArea\" tabIndex=\"0\"></div>");
    $("#mapArea").mousewheel(function (event, delta, deltaX, deltaY) {
        setZoom(zoom + .2 * delta);
    });
    oCenterMarker = new centerMarker();
    oMouseOverMarker = new mouseOverMarker();
    //<body onresize="resizeScreen();">
    $(window).resize(resizeScreen);
    resizeScreen();
    $("#mapArea").mousedown(function (e) {
        if (e.which == 1) {
            mousedown = true;
            var x = Math.round((e.pageX - centerPixelX) / (cellSize * zoom)) + centerX;
            var y = Math.round((e.pageY - centerPixelY - 20) / (cellSize * zoom)) + centerY;
            if (cells[y] === undefined) {
                addCells(e, x, y);
            } else if (cells[y][x] === undefined) {
                addCells(e, x, y);
            } else {
                updateCells(e, x, y);
            }
        }
    });
    $("#mapArea").mousemove(function (e) {
        var x = Math.round((e.pageX - centerPixelX) / (cellSize * zoom)) + centerX;
        var y = Math.round((e.pageY - centerPixelY - 20) / (cellSize * zoom)) + centerY;
        oMouseOverMarker.x(x);
        oMouseOverMarker.y(y);
        oMouseOverMarker.elevation($("#cboElevation").val());
        //console.log(e.pageX, e.pageY);
        if (mousedown) {
            if (cells[y] === undefined) {
                addCells(e, x, y);
            } else if (cells[y][x] === undefined) {
                addCells(e, x, y);
            } else {
                updateCells(e, x, y);
            }
        }
    });
    $("body").mouseup(function (e) {
        if (e.which == 1) {
            mousedown = false;
        }
    });
    $("#mapArea").mouseover(function (e) {
        if (e.which != 1 && mousedown) {
            mousedown = false;
        }
    });
    $("#mapArea").bind("keydown", function (e) {
        //console.log(e.type + ': ' + e.which);
        if (e.which == 87) {
            centerY--;
            bgRenderReset = true;
            calcMapVars();
            renderMap();
        } else if (e.which == 83) {
            centerY++;
            bgRenderReset = true;
            calcMapVars();
            renderMap();
        } else if (e.which == 65) {
            centerX--;
            bgRenderReset = true;
            calcMapVars();
            renderMap();
        } else if (e.which == 68) {
            centerX++;
            bgRenderReset = true;
            calcMapVars();
            renderMap();
        }
    });
});